package com.tsyc.contactdemo;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;

public class MainActivity extends PermissionActivity implements View.OnClickListener {

    private Context mContext;

    String[] permissions = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
    };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        Button mBtnCheck = findViewById(R.id.btn_check_permission);
        Button mBtnRead = findViewById(R.id.btn_read_contact);
        Button mBtnWrite = findViewById(R.id.btn_write_contact);
        Button mBtnDelete = findViewById(R.id.btn_delete_contact);
        mBtnCheck.setOnClickListener(this);
        mBtnRead.setOnClickListener(this);
        mBtnWrite.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_check_permission:
                checkPermission();
                break;
            case R.id.btn_read_contact:
                readContact();

                break;
            case R.id.btn_write_contact:
                writeContact();
                break;
            case R.id.btn_delete_contact:
//                deleteContact();
                deleteAllContact();
                break;

            default:
                break;
        }
    }

    private void checkPermission() {

        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            Toast.makeText(MainActivity.this, "已经授权", Toast.LENGTH_LONG).show();
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 200);
        }
    }

    private void writeContact() {
        getData();

        for (int i = 0; i < nameList.size(); i++) {
            final String name = nameList.get(i);
            final String phone = phoneList.get(i);
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
                    addContact(mContext,name , phone, "别名");
//                }
//            }).start();
        }
    }

    private void readContact() {
        // MainActivityPermissionsDispatcher.openPhoneStateWithPermissionCheck(MainActivity.this);
    }

    //删除所有
    private void deleteAllContact() {
        ContentResolver resolver = getContentResolver();
        Uri uri = ContactsContract.Contacts.CONTENT_URI;

        Cursor cursor = resolver.query(uri, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String rawContactId = "";
                // 从Contacts表当中取得ContactId
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Log.e("contactID", id+" =   dn"+displayName);
                // 获取RawContacts表的游标
                Cursor rawContactCur = resolver.query(ContactsContract.RawContacts.CONTENT_URI, null,
                        ContactsContract.RawContacts._ID + "=?", new String[]{id}, null);
                if (rawContactCur.moveToFirst()) {
                    // 读取第一条记录的RawContacts._ID列的值
                    rawContactId = rawContactCur.getString(rawContactCur
                            .getColumnIndex(ContactsContract.RawContacts._ID));
                }
                // 关闭游标
                rawContactCur.close();

                // ------------------------根据别名删除逻辑------------------------------
                Cursor phoneCursor3 = getContentResolver().query(
                        ContactsContract.Data.CONTENT_URI, null,
                        "raw_contact_id=? and " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[]{rawContactId, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}, null);
                if (phoneCursor3.moveToFirst()) {
                    String contactRemark = phoneCursor3.getString(phoneCursor3.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                    Log.e("备注新ixi     ",contactRemark);
                    if (contactRemark.equals("我是别名")) {
                        //根据名字获取id，删除id
                        String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        uri = Uri.parse("content://com.android.contacts/raw_contacts");
                        phoneCursor3 = getContentResolver().query(uri, new String[]{ContactsContract.Data._ID}, "display_name=?", new String[]{contactName}, null);
                        if (phoneCursor3.moveToFirst()) {
                            int ids = cursor.getInt(0);
                            //根据id删除data中的相应数据
                            getContentResolver().delete(uri, "display_name=?", new String[]{contactName});
                            uri = Uri.parse("content://com.android.contacts/data");
                            getContentResolver().delete(uri, "raw_contact_id=?", new String[]{ids + ""});
                        }
                    }else {
                        Toast.makeText(mContext, "导出数据已全部删除", Toast.LENGTH_SHORT).show();
                    }
                }
                //-------------------------跟别名删除逻辑结束---------------------
            }
            cursor.close();
        }
    }


    private void deleteContact() {
        ContentResolver resolver = getContentResolver();
        Uri uri = ContactsContract.Contacts.CONTENT_URI;

        Cursor cursor = resolver.query(uri, null, null, null, null);
        Log.e("cursor.lenght ", cursor.getCount() + "");
        if (cursor.getCount() > 0) { // 通讯录有多少条数据
            while (cursor.moveToNext()) {
                String rawContactId = "";
                // 从Contacts表当中取得ContactId
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

                String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Log.e("contactID", id+" =   dn"+displayName);
                // 获取RawContacts表的游标
                Cursor rawContactCur = resolver.query(ContactsContract.RawContacts.CONTENT_URI, null,
                        ContactsContract.RawContacts._ID + "=?", new String[]{id}, null);
                // 该查询结果一般只返回一条记录，所以我们直接让游标指向第一条记录
                if (rawContactCur.moveToFirst()) {
                    // 读取第一条记录的RawContacts._ID列的值
                    rawContactId = rawContactCur.getString(rawContactCur
                            .getColumnIndex(ContactsContract.RawContacts._ID));
                    String string = rawContactCur.getString(rawContactCur.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY));
                    Log.e("rawContactID", rawContactId + " -  通讯录名：" + string);
                }
                // 关闭游标
                rawContactCur.close();

                // ------------------------根据别名删除逻辑------------------------------
                Cursor phoneCursor3 = getContentResolver().query(
                        ContactsContract.Data.CONTENT_URI, null,
                        "raw_contact_id=? and " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[]{rawContactId, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}, null);
                if (phoneCursor3.moveToFirst()) {
                    String contactRemark = phoneCursor3.getString(phoneCursor3.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                    Log.e("备注新ixi     ",contactRemark);
                    if (contactRemark.equals("我是别名")) {
                        //根据名字获取id，删除id
                        String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                        uri = Uri.parse("content://com.android.contacts/raw_contacts");
                        phoneCursor3 = getContentResolver().query(uri, new String[]{ContactsContract.Data._ID}, "display_name=?", new String[]{contactName}, null);
                        if (phoneCursor3.moveToFirst()) {
                            int ids = cursor.getInt(0);
                            //根据id删除data中的相应数据
                            getContentResolver().delete(uri, "display_name=?", new String[]{contactName});
                            uri = Uri.parse("content://com.android.contacts/data");
                            getContentResolver().delete(uri, "raw_contact_id=?", new String[]{ids + ""});
                        }
                    }
                }
                //-------------------------跟别名删除逻辑结束---------------------

                // 读取号码
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // 根据查询RAW_CONTACT_ID查询该联系人的号码
                    Cursor phoneCur = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID
                                    + "=?",
                            new String[]{rawContactId}, null);
                    // 上面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                    // 可以用下面的phoneUri代替
                    // Uri
                    // phoneUri=Uri.parse("content://com.android.contacts/data/phones");

                    // 一个联系人可能有多个号码，需要遍历
                    while (phoneCur.moveToNext()) {
                        // 获取号码
                        String number = phoneCur
                                .getString(phoneCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        String phoneCur_remark = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                        String phoneCur_remark2 = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.PHONETIC_NAME));

                        Log.e("number", number + " =- " +phoneCur_remark2+ "-= " + phoneCur_remark);
                        // 获取号码类型
                        String type = phoneCur
                                .getString(phoneCur
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                        Log.e("type", type);

                    }
                    phoneCur.close();

                }
            }
            cursor.close();

        }
    }

    public static void addContact(Context context, String name, String phoneNumber, String bm) {
        try {

            // 创建一个空的ContentValues
            ContentValues values = new ContentValues();
            // 向RawContacts.CONTENT_URI空值插入，
            // 先获取Android系统返回的rawContactId
            // 后面要基于此id插入值
            Uri rawContactUri = context.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
            long rawContactId = ContentUris.parseId(rawContactUri);
            values.clear();

            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            // 内容类型
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            // 联系人名字
            values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
            // 向联系人URI添加联系人名字
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();

            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            // 联系人的电话号码
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
            // 电话类型
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);

            // 向联系人电话号码URI添加电话号码
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();

            //设置备注
            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
            //写入别名
            values.put(ContactsContract.CommonDataKinds.Note.NOTE, "我是别名");//备注
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();

            //设置群组
            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
            //写入别名
            values.put(ContactsContract.CommonDataKinds.Organization.COMPANY, "这是一个群组");//备注
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();
            Toast.makeText(context, "联系人数据添加成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("____", e.getMessage());
        }
    }


    @NeedsPermission({Manifest.permission.WRITE_CONTACTS})
    void openPhoneState() {
        addContact(mContext, "AAAA", "18888888888", "");
    }

    @OnPermissionDenied({Manifest.permission.WRITE_CONTACTS})
    void showDeniedForContacts() {
        Toast.makeText(mContext, "您拒绝了写入通讯录的权限，添加到通讯录失败。", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.WRITE_CONTACTS})
    void showNeverAskForContacts() {
        Toast.makeText(mContext, "当前功能需要在设置-应用-千客家-权限中开启读写通讯录权限。", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        //   MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);

        if (requestCode == 200) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showToast("权限已申请");
            } else {
                showToast("权限已拒绝");
            }
        } else if (requestCode == 200) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        showToast("权限未申请");
                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void showToast(String content) {

        Toast.makeText(mContext, content, Toast.LENGTH_SHORT).show();

    }

    List<String> nameList = new ArrayList<>();
    List<String> phoneList = new ArrayList<>();

    private void getData() {
        for (int i = 0; i < 6; i++) {
            nameList.add("姓名" + i);
            phoneList.add("1555555555" + i);
        }
    }


}
